package cn.nit.blog.controller;

import cn.nit.blog.entity.User;
import cn.nit.blog.exception.BlogException;
import cn.nit.blog.service.IUserService;
import cn.nit.blog.vo.RePassVo;
import cn.nit.blog.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wjx
 * @since 2023-03-21
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;
    
    @PostMapping("/register")
    public String register(UserVo userVo) {

        // 1.做校验，有问题则返回异常信息
        if (ObjectUtils.isEmpty(userVo.getUsername())) {
            throw new BlogException(1001, "用户名不能为空");
        }

        if (ObjectUtils.isEmpty(userVo.getPwd())) {
            throw new BlogException(1001, "密码不能为空");
        }

        if (ObjectUtils.isEmpty(userVo.getEmail())) {
            throw new BlogException(1001, "邮箱不能为空");
        }

        // 实现注册
        userService.register(userVo);

//        返回一个页面
        return "redirect:/site/registerSuccess.html";
    }

    @RequestMapping("/activation")
    public String Activation(String code){
        // 1.非空校验
        if (ObjectUtils.isEmpty(code)) {
            throw new BlogException(1001, "code不能为空");
        }

        // 2.根据你的激活码
        Integer status = userService.updateUserStatus(code);
        if (status <= 0) {
            throw new BlogException(1002, "激活有误或者账号已经激活");
        }
        return "redirect:/site/login.html";
    }

    @PostMapping("/login")
    public String login(UserVo userVo, HttpSession httpSession){

//        判断是否为空
        if (ObjectUtils.isEmpty(userVo.getUsername())){
            throw new BlogException(1002, "请填写用户名");
        }

        if (ObjectUtils.isEmpty(userVo.getPwd())){
            throw new BlogException(1002, "请填写密码");
        }
//        用用户名验证用户是否存在
        User user = userService.getUserByUsername(userVo.getUsername());
        if (user == null){
            throw new BlogException(1002, "用户名不存在");
        }
//        验证密码是否正确
        boolean checkpw = BCrypt.checkpw(userVo.getPwd(), user.getPassword());
        if (!checkpw){
            throw  new BlogException(1004, "用户名或密码错误");
        }
//        验证用户是否激活
        if (user.getStatus() != 1) {
            throw  new BlogException(1004, "用户未激活");
        }
//        放入session
        user.setPassword(null);
        httpSession.setAttribute("loginUser", user);

//        成功则返回login 页面
        return "redirect:/";
    }

//    个人主页
    @GetMapping("/info/{id}")
    public String info(@PathVariable Integer id, Model model){
//        获取个人的信息：头像，用户名，创建时间
        User user = userService.getById(id);
        user.setPassword(null);

//        获取点赞数，粉丝，我的关注，
        Integer followerCount = 10;
        Integer fansCount = 20;
        Integer userLikeCount = 30;

//        把相关信息放进model中
        model.addAttribute("user",user);
        model.addAttribute("followerCount",followerCount);
        model.addAttribute("fansCount",fansCount);
        model.addAttribute("userLikeCount",userLikeCount);
        model.addAttribute("hasFollowed",true);

//        返回个人主页界面
        return "site/profile";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
//        注销session
        session.invalidate();
//        重定向到首页
        return "redirect:/";
    }

    @PostMapping("/repass")
    public String password(HttpSession session, String oldPassword, String newPassword, String confirmPassword){

//        数据校验
        dataValidate(oldPassword, newPassword, confirmPassword);

//        根据用户名查询密码与用户填写的密码进行比对
        User loginUser = (User) session.getAttribute("loginUser");
        User user = userService.getUserByUsername(loginUser.getUsername());
        boolean checkpw = BCrypt.checkpw(oldPassword, user.getPassword());

//        正确则进行密码的修改
        if (!checkpw){
           throw new BlogException(1005, "原密码填写错误！");
        }

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        String newHashPw = BCrypt.hashpw(newPassword, BCrypt.gensalt());
        updateWrapper.set("password",newHashPw).eq("id",user.getId());
        boolean update = userService.update(updateWrapper);

        if (update) {
            System.out.println("密码修改成功！");
        }

//        返回登录页面
        return "redirect:/site/login.html";
    }

    @PostMapping("/temp")
    public String repass(RePassVo rePassVo){
//        数据校验
        dataValidate(rePassVo);

//        根据id在数据库中查询用户
        return null;
    }

    private void dataValidate(String oldPassword, String newPassword, String confirmPassword) {
        if(ObjectUtils.isEmpty(oldPassword)){
            throw new BlogException(1001, "请填写旧密码");
        }
        if(ObjectUtils.isEmpty(newPassword)){
            throw new BlogException(1001, "请填写新密码");
        }
        if(ObjectUtils.isEmpty(confirmPassword)){
            throw new BlogException(1001, "请填写确认密码");
        }
        if (!newPassword.equals(confirmPassword)){
            throw new BlogException(1003, "新密码与确认密码不一致！");
        }
    }

    private void dataValidate(RePassVo rePassVo) {
        if(ObjectUtils.isEmpty(rePassVo.getOldPassword())){
            throw new BlogException(1001, "请填写旧密码");
        }
        if(ObjectUtils.isEmpty(rePassVo.getNewPassword())){
            throw new BlogException(1001, "请填写新密码");
        }
        if(ObjectUtils.isEmpty(rePassVo.getConfirmPassword())){
            throw new BlogException(1001, "请填写确认密码");
        }
        if (!rePassVo.getNewPassword().equals(rePassVo.getConfirmPassword())){
            throw new BlogException(1003, "新密码与确认密码不一致！");
        }
    }

}
